import { useState } from "react"

export type UseToggleReturn = [
  boolean,
  {
    open(): void;
    close(): void;
    toggle(): void;
    set(value: boolean): void;
  }
]

/** 状态切换
 * @param defaultValue 默认值
 * @example
 * ```tsx
 * const [isOpen, { open, close, toggle, set }] = useToggle(false)
 *
 * <span>{String(isOpen)}</span>
 * <button onClick={toggle}>打开/关闭</button>
 * ```
 */
export default (defaultValue: boolean = false): UseToggleReturn => {
  const [state, setState] = useState(defaultValue)

  return [
    state,
    {
      open: () => setState(true),
      close: () => setState(false),
      toggle: () => setState(!open),
      set: (value: boolean) => setState(value),
    }
  ]
}
